# -*- coding: utf-8 -*-

# graphic-pppoe-client - Easy graphic networking manager
#
# Author: GoTLiuM InSPiRiT <gotlium@gmail.com>
#
# Copyright 2010, GoTLiuM InSPiRiT <gotlium@gmail.com>.
#
# This program is free software: you can redistribute it and/or modify it
# under the terms of the GNU General Public License version 2, as published
# by the Free Software Foundation.
#
# This program is distributed in the hope that it will be useful, but
# WITHOUT ANY WARRANTY; without even the implied warranties of
# MERCHANTABILITY, SATISFACTORY QUALITY, or FITNESS FOR A PARTICULAR
# PURPOSE.  See the GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License along
# with this program.  If not, see <http://www.gnu.org/licenses/>.

import threading
import SocketServer
from time import sleep

def dMessage(status, message):
	mStatus = 'ERROR'
	if status == 0:
		mStatus = 'OK'
	return '%s: %s' % (mStatus, str(message))

class ThreadedTCPServer(SocketServer.ThreadingMixIn, SocketServer.TCPServer):
    pass

class Server(SocketServer.BaseRequestHandler):
	def _initServer(self, serverConfig):
		GPD_INSTANCE = self
		class ThreadedTCPRequestHandler(SocketServer.BaseRequestHandler):
			def readOnly(self):
				import time
				count = len(GPD_INSTANCE._getModulesEvents())
				while True:
					for event in GPD_INSTANCE._getModulesEvents()[count:]:
						event = str(event)
						self.request.send(event + "\n")
						count += 1
					time.sleep(2)

			def readWrite(self):
				request = ""
				while True:
					data = readed = ""
					while True:
						readed = self.request.recv(1024)
						data += readed
						if not readed or data[-1] == '\n':
							break
					if data.strip() in ('QUIT', 'quit', 'bye'):
						self.request.send("OK\n")
						break
					request += data.strip()
					if not data or data[-1:] == "\n":
						response = GPD_INSTANCE._callModule(request)
						response = str(response).strip()
						self.request.sendall(response + "\n")
						request = response = data = readed = ""

			def handle(self):
				#try:
				if 1:
					data = self.request.recv(1024).strip()
					if data == "LISTEN":
						self.request.send("OK\n")
						self.readOnly()
					elif data== "EXCHANGE":
						self.request.send("OK\n")
						self.readWrite()
					else:
						self.request.send("ERROR\n")
				#except:
				#	pass

		server = ThreadedTCPServer(serverConfig, ThreadedTCPRequestHandler)
		server_thread = threading.Thread(target=server.serve_forever)

		server_thread.daemon = True
		server_thread.start()

		try:
			while True:
				sleep(60)
		except:
			pass

		server.shutdown()
